package top.lyc829.zzl_android.ui.travel.edit_travel;

import androidx.lifecycle.ViewModelProvider;

import android.annotation.TargetApi;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.base.XPageFragment;
import com.xuexiang.xpage.utils.TitleBar;
import com.xuexiang.xui.utils.StatusBarUtils;

import java.util.ArrayList;

import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.logic.bean.TravelItemBean;
import top.lyc829.zzl_android.logic.util.RichUtils;
import top.lyc829.zzl_android.logic.util.Utils;

@Page(name = "PreviewTravelFragment")
public class PreviewTravelFragment extends XPageFragment {

    private WebView preViewWebView;
    private TextView titleTextView, txtFinish;
    private EditTravelViewModel mViewModel;

    @Override
    protected TitleBar initTitleBar() {
        return null;
    }

    public static PreviewTravelFragment newInstance() {
        return new PreviewTravelFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.preview_travel_fragment;
    }

    @Override
    protected void initViews() {
        LinearLayout leoBarPreview = findViewById(R.id.leoBar_preview);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) leoBarPreview.getLayoutParams();
        lp.setMargins(0, StatusBarUtils.getStatusBarHeight(getContext()), 0, 0);
        leoBarPreview.setLayoutParams(lp);

        preViewWebView = findViewById(R.id.preview_webView);
        titleTextView = findViewById(R.id.txt_title_preview);
        txtFinish = findViewById(R.id.txt_finish_preview);
        mViewModel = new ViewModelProvider(getActivity()).get(EditTravelViewModel.class);

        clickListener();

        observer();

    }

    private void clickListener() {
        txtFinish.setOnClickListener(v -> popToBack());
    }

    private void observer() {
        mViewModel.getItemTravelLiveData().observe(getViewLifecycleOwner(), travelItemBeans -> {
            StringBuilder stringBuilder = new StringBuilder();
            for (TravelItemBean item : travelItemBeans) {
                stringBuilder.append(item.getText());
                stringBuilder.append("<br>");   //两个子游记之间需要换行。
            }
            initWebView(stringBuilder.toString());
        });
        mViewModel.getTravelTitleLiveData().observe(getViewLifecycleOwner(), s -> {
            titleTextView.setText(s);
            titleTextView.requestFocus();
        });
    }

    public void initWebView(String data) {

        WebSettings settings = preViewWebView.getSettings();

        //settings.setUseWideViewPort(true);//调整到适合webview的大小，不过尽量不要用，有些手机有问题
        settings.setAllowFileAccess(true);
        settings.setLoadWithOverviewMode(true);//设置WebView是否使用预览模式加载界面。
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setAllowFileAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);


        preViewWebView.setVerticalScrollBarEnabled(false);//不能垂直滑动
        preViewWebView.setHorizontalScrollBarEnabled(false);//不能水平滑动
        settings.setTextSize(WebSettings.TextSize.NORMAL);//通过设置WebSettings，改变HTML中文字的大小
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
        //设置WebView属性，能够执行Javascript脚本
        preViewWebView.getSettings().setJavaScriptEnabled(true);//设置js可用

        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容重新布局
        preViewWebView.setWebViewClient(webViewClient);
        preViewWebView.setWebChromeClient(new WebChromeClient());
        data = "</Div><head><style>body{font-size:16px}</style>" +
                "<style>img{ width:100% !important;margin-top:0.4em;margin-bottom:0.4em}</style>" +
                "<style>ul{ padding-left: 1em;margin-top:0em}</style>" +
                "<style>ol{ padding-left: 1.2em;margin-top:0em}</style>" +
                "</head>" + data;

//        ArrayList<String> arrayList = RichUtils.returnImageUrlsFromHtml(data);
//        if (arrayList.size() > 0) {
//            for (int i = 0; i < arrayList.size(); i++) {
//                if (!arrayList.get(i).contains("http")) {
//                    //如果不是http,那么就是本地绝对路径，要加上file
//                    data = data.replace(arrayList.get(i), "file://" + arrayList.get(i));
//                }
//            }
//        }

        preViewWebView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
    }

    public WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }


        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }


        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            return super.shouldOverrideUrlLoading(view, request);
        }


    };

    @Override
    protected void initListeners() {

    }


}